package com.xmy.cultivate.service.impl;

import com.aliyun.facebody20191230.models.AddFaceResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.StudentFaceDataMapper;
import com.xmy.cultivate.respons.ResFaceData;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 人脸采集 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-03-20
 */
@Service
public class StudentFaceDataServiceImpl extends ServiceImpl<StudentFaceDataMapper, StudentFaceData> implements IStudentFaceDataService {

    @Autowired
    StudentFaceDataMapper studentFaceDataMapper;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IFaceDbService iFaceDbService;

    @Autowired
    @Lazy
    IAliyunFaceService iAliyunFaceService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    IdWorker idWorker;

    @Override
    public boolean changeSchoolUpdateFace(ChangeSchoolDetail changeSchoolDetail) throws Exception {

        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("school_id",changeSchoolDetail.getInSchoolId());
        studentFaceDataQueryWrapper.eq("student_id",changeSchoolDetail.getStudentId());
        Long count = studentFaceDataMapper.selectCount(studentFaceDataQueryWrapper);


        Organization inSchool = iOrganizationService.getById(changeSchoolDetail.getInSchoolId());
        Organization outSchool = iOrganizationService.getById(changeSchoolDetail.getOutSchoolId());

        boolean isEqFace = false;//是否使用相同的人脸库
        if (inSchool.getAccessKeyId().equals(outSchool.getAccessKeyId())){
            isEqFace = true;
        }

        if (count.equals(0L)){
            studentFaceDataQueryWrapper.clear();
            studentFaceDataQueryWrapper.eq("school_id",changeSchoolDetail.getOutSchoolId());
            studentFaceDataQueryWrapper.eq("student_id",changeSchoolDetail.getStudentId());
            List<StudentFaceData> studentFaceDataList = studentFaceDataMapper.selectList(studentFaceDataQueryWrapper);
            for (StudentFaceData studentFaceData:studentFaceDataList){
                StudentFaceData studentFaceDataNew = new StudentFaceData();
                BeanUtils.copyProperties(studentFaceData,studentFaceDataNew);
                studentFaceDataNew.setId(idWorker.nextId());
                studentFaceDataNew.setSchoolId(changeSchoolDetail.getInSchoolId());
                studentFaceDataNew.setCreatedAt(LocalDateTime.now().withNano(0));

                //不相同人脸数据库
                if (!isEqFace){
                    studentFaceDataNew.setEntityId(null);
                    studentFaceDataNew.setFaceId(null);
                    studentFaceDataNew.setQualitieScore(null);
                    //studentFaceDataMapper.updateNotSign(studentFaceDataNew.getId());
                }
                studentFaceDataMapper.insert(studentFaceDataNew);
                this.setData(studentFaceDataNew.getSchoolId(),studentFaceDataNew.getStudentId().toString(),studentFaceDataNew.getOssImage(),studentFaceDataNew,studentFaceData.getFaceType());
            }
        }
        return true;
    }

    /**
     * 添加人脸数据
     *
     * @param schoolId
     * @param studentId
     * @param ossImageUrl
     * @param studentFaceDataOld
     * @return
     * @throws Exception
     */
    @Override
    public boolean setData(Long schoolId, String studentId, String ossImageUrl, StudentFaceData studentFaceDataOld, Integer faceType) throws Exception {
        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);
        if (faceType.equals(1)){
            Student student = iStudentService.getById(studentId);
            String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), schoolId, ossImageUrl);
            if (faceIdAndentityId != null && !faceIdAndentityId.equals("error")) {
                String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
                String faceId = faceIdAndEntityIdArr[0];
                String entityId = faceIdAndEntityIdArr[1];
                if (studentId != entityId) {
                    student.setIsGather(1);
                    student.setEntityId(entityId);
                    iStudentService.updateById(student);
                    studentFaceDataOld.setFaceId(faceId);
                    studentFaceDataOld.setEntityId(Long.parseLong(entityId));
                    studentFaceDataOld.setUpdateLevel(1);
                    this.updateById(studentFaceDataOld);
                    return true;
                }
            } else if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
                return false;
            }

            if (iAliyunFaceService.existFaceSample(schoolId, faceDb.getDbName(), student.getId().toString())) {
                iAliyunFaceService.updateFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
            } else {
                iAliyunFaceService.addFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
            }

            student.setIsGather(1);//设置为已采集
            QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
            String extraData = student.getName().trim();
            AddFaceResponse addFaceResponse = iAliyunFaceService.addFaceData(schoolId, faceDb.getDbName(), ossImageUrl, student.getId().toString(), extraData);//添加人脸数据

            if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
                studentFaceDataOld.setEntityId(studentFaceDataOld.getStudentId());
                studentFaceDataOld.setFaceId(addFaceResponse.getBody().getData().faceId);
                studentFaceDataOld.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                studentFaceDataOld.setUpdateLevel(1);
                this.updateById(studentFaceDataOld);
                //System.out.println("采集成功,faceId:" + studentFaceDataOld.getFaceId());
                return true;
            } else {
                if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                    return false;
                } else {
                    return false;
                }
            }
        }else{
            Staff staff = iStaffService.getById(studentId);
            String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), schoolId, ossImageUrl);
            if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
                return false;
            }

            if (iAliyunFaceService.existFaceSample(schoolId, faceDb.getDbName(), staff.getId().toString())) {
                iAliyunFaceService.updateFaceSample(schoolId, faceDb.getDbName(), staff.getId().toString(), staff.getName());//添加人脸样本
            } else {
                iAliyunFaceService.addFaceSample(schoolId, faceDb.getDbName(), staff.getId().toString(), staff.getName());//添加人脸样本
            }

            staff.setIsGather(1);//设置为已采集
            QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
            String extraData = staff.getName().trim();
            AddFaceResponse addFaceResponse = iAliyunFaceService.addFaceData(schoolId, faceDb.getDbName(), ossImageUrl, staff.getId().toString(), extraData);//添加人脸数据

            if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
                studentFaceDataOld.setEntityId(studentFaceDataOld.getStudentId());
                studentFaceDataOld.setFaceId(addFaceResponse.getBody().getData().faceId);
                studentFaceDataOld.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                studentFaceDataOld.setUpdateLevel(1);
                this.updateById(studentFaceDataOld);
                //System.out.println("采集成功,faceId:" + studentFaceDataOld.getFaceId());
                return true;
            } else {
                if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                    return false;
                } else {
                    return false;
                }
            }
        }
    }


    /**
     * 更新多人脸数据库数据
     * @param schoolId
     * @param studentFaceManyDetail
     * @return
     * @throws Exception
     */
    @Override
    public ResFaceData setDataForMany(Long schoolId, StudentFaceManyDetail studentFaceManyDetail, Integer faceType) throws Exception {
        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);
        ResFaceData resFaceData = new ResFaceData();
        //学生
        if (faceType.equals(1)){
            Student student = iStudentService.getById(studentFaceManyDetail.getStudentId());
            String studentId = student.getId().toString();
            if (student == null){
                resFaceData.setCode(Code.ERROR);
                resFaceData.setMsg("学生不存在");
                return resFaceData;
            }

            String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), schoolId, studentFaceManyDetail.getOssImage());
            if (faceIdAndentityId != null && !faceIdAndentityId.equals("error")) {
                String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
                String faceId = faceIdAndEntityIdArr[0];
                String entityId = faceIdAndEntityIdArr[1];
                if (studentId != entityId) {
                    Student studentEntity = iStudentService.getById(entityId);
                    if (studentEntity != null){
                        //并且名字相同
                        if (student.getName().trim().equals(studentEntity.getName().trim())){
                            resFaceData.setCode(Code.OK);
                            resFaceData.setEntityId(Long.parseLong(entityId));
                            resFaceData.setStudentId(Long.parseLong(studentId));
                            resFaceData.setFaceId(faceId);
                            return resFaceData;
                        }
                    }
                }
            } else if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
                resFaceData.setCode(Code.ERROR);
                resFaceData.setMsg("搜索人脸报错");
                return resFaceData;
            }

            //人脸样本是否存在
            if (iAliyunFaceService.existFaceSample(schoolId, faceDb.getDbName(), student.getId().toString())) {
                iAliyunFaceService.updateFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//更新人脸样本
            } else {
                iAliyunFaceService.addFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
            }

            String extraData = student.getName().trim();
            AddFaceResponse addFaceResponse = iAliyunFaceService.addFaceData(schoolId, faceDb.getDbName(), studentFaceManyDetail.getOssImage(), student.getId().toString(), extraData);//添加人脸数据

            if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
                //System.out.println("采集成功,faceId:" + studentFaceDataOld.getFaceId());
                resFaceData.setCode(Code.OK);
                resFaceData.setEntityId(student.getId());
                resFaceData.setStudentId(student.getId());
                resFaceData.setFaceId(addFaceResponse.getBody().getData().faceId);
                resFaceData.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                return resFaceData;
            } else {
                if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                    resFaceData.setCode(Code.ERROR);
                } else {
                    resFaceData.setCode(Code.ERROR);
                }
                resFaceData.setMsg("添加人脸报错");
                return resFaceData;
            }
        }else{//教师
            Staff staff = iStaffService.getById(studentFaceManyDetail.getStudentId());
            if (staff == null){
                resFaceData.setCode(Code.ERROR);
                resFaceData.setMsg("老师不存在");
                return resFaceData;
            }

            String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), schoolId, studentFaceManyDetail.getOssImage());
            if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
                resFaceData.setCode(Code.ERROR);
                resFaceData.setMsg("搜索人脸报错");
                return resFaceData;
            }

            //人脸样本是否存在
            if (iAliyunFaceService.existFaceSample(schoolId, faceDb.getDbName(), staff.getId().toString())) {
                iAliyunFaceService.updateFaceSample(schoolId, faceDb.getDbName(), staff.getId().toString(), staff.getName());//更新人脸样本
            } else {
                iAliyunFaceService.addFaceSample(schoolId, faceDb.getDbName(), staff.getId().toString(), staff.getName());//添加人脸样本
            }

            String extraData = staff.getName().trim();
            AddFaceResponse addFaceResponse = iAliyunFaceService.addFaceData(schoolId, faceDb.getDbName(), studentFaceManyDetail.getOssImage(), staff.getId().toString(), extraData);//添加人脸数据

            if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
                //System.out.println("采集成功,faceId:" + studentFaceDataOld.getFaceId());
                resFaceData.setCode(Code.OK);
                resFaceData.setEntityId(staff.getId());
                resFaceData.setStudentId(staff.getId());
                resFaceData.setFaceId(addFaceResponse.getBody().getData().faceId);
                resFaceData.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                return resFaceData;
            } else {
                if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                    resFaceData.setCode(Code.ERROR);
                } else {
                    resFaceData.setCode(Code.ERROR);
                }
                resFaceData.setMsg("添加人脸报错");
                return resFaceData;
            }
        }

    }
}
